package com.lkd.http.controller;
import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/requestPay")
    public Map requestPay(@RequestBody PayVO payVO){

        //1.生成订单
        OrderEntity order = orderService.createOrder(payVO);

        //2.生成支付记录
        WxPayParam param = new WxPayParam();
        param.setOutTradeNo(order.getOrderNo());
        param.setOpenid(payVO.getOpenId());
        param.setTotalFee(order.getAmount());
        param.setBody(order.getSkuName());
        Map<String, String> map = this.wxPayTemplate.requestPay(param);
        return map;
    }

    //http://793f09e2.r5.cpolar.top/order/payNotify

    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response){

        try {
            Map<String, String> result = wxPayTemplate.validPay(request.getInputStream());
            if("SUCCESS".equals( result.get("code") )){  //返回码成功
                String orderSn= result.get("order_sn");//获取订单号
                log.info("支付成功，修改订单状态和支付状态，订单号：{}",orderSn);

                //支付成功，修改订单状态
                OrderEntity order = orderService.getByOrderNo(orderSn);
                if(order == null){
                    log.error("订单被删除了" + orderSn );
                    //给微信支付一个成功的响应
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                    return;
                }

                order.setPayStatus(VMSystem.PAY_STATUS_PAYED);
                order.setStatus(VMSystem.ORDER_STATUS_PAYED);
                order.setThirdNo(result.get("transaction_id"));
                orderService.updateById(order);
            }
            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            response.getWriter().write(WXConfig.RESULT);
        }catch (Exception e){
            log.error("支付回调处理失败",e);
        }
    }
}
